import subprocess
import os  
import re

file_path = 'check.py'

class RequireClassifier:
    def __init__(self):
        self.require_flag = False
        self.require_command = []
        self.require_kind = ''
        self.code_flag = False
        self.say_flag = False
        self.result_flag = False
        self.all_require = ['质量检测', '质量评估', '质量分析', '质量', '提升', 'pep', 'PEP']
        self.E_require = ['错误', '失败', '不对', '不正确', '改正', '修改']
        self.W_require = ['警告', '小问题', '修改']
        self.C_require = ['风格', '习惯', '规范', '约定']
        self.R_require = ['重构', '结构', '冗余', '性能']
        self.bandit_require = ['安全', '危险', '风险', '漏洞']
        self.black_require = ['改善代码格式', '优化代码格式', '改善格式', '优化格式', '改进格式', '改正', '格式化']
    
    def classify(self, require):
        for keyword in self.all_require:
            if keyword in require:
                self.require_command = ['pylint', file_path] 
                self.require_flag = True
                self.require_kind = 'pylint'
                return
        for keyword in self.E_require:
            if keyword in require:
                if len(self.require_command) == 0:
                    self.require_command = ['pylint', '--disable=all', '--enable=E']
                else:
                    self.require_command.append('--enable=E')
                self.require_flag = True
                break
        for keyword in self.W_require:
            if keyword in require:
                if len(self.require_command) == 0:
                    self.require_command = ['pylint', '--disable=all', '--enable=W']
                else:
                    self.require_command.append('--enable=W')
                self.require_flag = True
                break
        for keyword in self.C_require:
            if keyword in require:
                if len(self.require_command) == 0:
                    self.require_command = ['pylint', '--disable=all', '--enable=C']
                else:
                    self.require_command.append('--enable=C')
                self.require_flag = True
                break
        for keyword in self.R_require:
            if keyword in require:
                if len(self.require_command) == 0:
                    self.require_command = ['pylint', '--disable=all', '--enable=R']
                else:
                    self.require_command.append('--enable=R')
                self.require_flag = True
                break
        if self.require_flag:
            self.require_command.append(file_path)
            self.require_kind = 'pylint'
        
        for keyword in self.bandit_require:
            if keyword in require:
                if len(self.require_command) == 0:
                    self.require_command = ['bandit', file_path]
                    self.require_flag = True
                    self.require_kind = 'bandit'
                    return
                break
        for keyword in self.black_require:
            if keyword in require:
                if len(self.require_command) == 0:
                    self.require_command = ['black', '-q', file_path]
                    self.require_flag = True
                    self.require_kind = 'black'
                    return
                break
        
        return

    def split_require_code(self, text):
        chinese_punctuation = r'，。！？；：“”‘’（）《》〈〉【】『』「」【】'  
        chinese_pattern = re.compile(rf'^([\s]*[{re.escape(chinese_punctuation)}\u4e00-\u9fa5]+[\s]*)+$', re.MULTILINE) 
        
        requires = chinese_pattern.findall(text)  

        code = re.sub(rf'^([\s]*[{re.escape(chinese_punctuation)}\u4e00-\u9fa5]+[\s]*)+$', '', text, flags=re.MULTILINE)    
        
        # 打印结果  
        all_requires = '，'.join(requires) if requires else ''
        # print(f'all_requires: {all_requires}')
        # print(f'code: {code}')
        self.classify(all_requires)

        
        if len(code):
            with open(file_path, 'w', encoding='utf-8') as file:
                file.write(code)
            self.code_flag = True
            self.say_flag = False
        
        return all_requires

    def run_result(self,text):
        final_result = []
        all_requires = self.split_require_code(text)
        if self.code_flag == True and self.require_flag == True:
            # 使用subprocess.run来执行命令   
            check_result = subprocess.run(self.require_command, capture_output=True, text=True)  
        
            # 如果返回了非零退出码，说明有消息 
            if check_result.returncode != 0:
                # 下面是使用pylint的情况
                if self.require_kind == 'pylint':
                    results = [line for line in check_result.stdout.split('\n') if line.startswith(file_path)]
                    if len(results)!=0:
                        for result in results:
                            parts = result.split(':')
                            line = parts[1]
                            column = parts[2]
                            error_code = parts[3]
                            description = parts[4]
                            description = re.sub(r'\(.*?\)', '', description, flags=re.S)
                            final_result.append(f"第{line}行, 第{column}列, 问题编号:{error_code},问题: {description}")
                        final_result = "\n".join(final_result)
                # 下面是使用bandit的情况
                elif self.require_kind == 'bandit':
                    start_marker = 'Test results:'
                    end_marker = 'Code scanned:'
                    start_index = check_result.stdout.index(start_marker) + len(start_marker)
                    end_index = check_result.stdout.find(end_marker)
                    if end_index != -1:
                        test_results = check_result.stdout[start_index:end_index]
                    else:
                        test_results = check_result.stdout[start_index:]
                    translations = {
                            "Issue": "问题",
                            "Severity": "严重性",
                            "Confidence": "置信度",
                            "More Info": "更多信息",
                            "Location": "位置",
                        }
                    final_result = []
                    lines = test_results.split("\n")
                    for line in lines:
                        for english, chinese in translations.items():
                            if english in line:
                                line = line.replace(english, chinese)
                        final_result.append(line)
                    final_result = "\n".join(final_result)
                elif self.require_kind == 'black':
                    parts = check_result.stderr.split(':')
                    line = parts[3]
                    column = parts[4]
                    description = parts[5].rstrip('\n')
                    description = re.sub(r'\(.*?\)', '', description, flags=re.S)
                    final_result = f"第{line}行,第{column}列:{description}无法格式化"
            else:
                if self.require_kind == 'black':
                    final_result = "已完成对代码格式的规范化"
                else:
                    final_result = "您的代码在这方面没有问题"
            # 处理完需求等待下一次需求
            self.result_flag = True
            self.require_flag = False
            self.require_command = []

        elif self.code_flag == True and self.require_flag == False and self.say_flag == False:
            final_result = "请输入您的需求"
            self.say_flag = True
            self.result_flag = True
        elif self.code_flag == False and self.require_flag == True and self.say_flag == False:
            final_result = "请输入您的代码"
            self.say_flag = True
            self.result_flag = True
        else:
            final_result = all_requires
            self.result_flag = False
        # print("require_flag:",self.require_flag,"code_flag:",self.code_flag)
        return final_result
    

if __name__ == '__main__':
    handler = RequireClassifier()
    
    question =  """
你好？
# 这是一个汉字说明
## 描述了下面代码的功能

def hello_world():  
    print("Hello, World!")

检查代码

# 这是另一个汉字说明  
# 关于另一个函数  

def add_numbers(a, b):  
    return a + b  
    """
    # while 1:
    # question = input("用户:")
    data = handler.run_result(question)
    print(data)